// pages/shoppingCar/shoppingCar.js
const util = require('../../utils/util.js');
const app = getApp() 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasList:false,
    totalPrice:0,
    selectAllStatus:false,
    startX: 0, //开始坐标
    startY: 0,
    carts:[]
  },
  getTitleById(id){
    util.post({
      url:"https://groomtea.icebartech.com/api/miniApp/product/productDetail?id="+id,
      success:(res)=>{
        console.log(res)
      }
    })
  },
  getTotalPrice:function(){
    let carts = this.data.carts;
    let total = 0;
    for(let i = 0;i<carts.length;i++){
      carts[i].cost = (carts[i].primeCost * carts[i].bagNum) || (carts[i].primeCost*carts[i].pieceNum * carts[i].specification)
      if(carts[i].selected){
        total += carts[i].cost;
      }
    }
    this.setData({
      totalPrice: total.toFixed(2)
    })
  },
  bindSubmit:function(){
    let carts = this.data.carts;
    const goods = [];
    for (let i = 0; i < carts.length; i++) {
      if (carts[i].selected) {
        carts[i].pictureUrl = encodeURIComponent(carts[i].pictureUrl)
        goods.push(carts[i]);
      }
    }
    console.log(goods);
    if(!goods.length){
      wx.showToast({
        title: '请选择需要购买的茶叶',
        icon:'none',
        duration: 2000
      })
    }else{
      wx.navigateTo({
        url: `../balance/balance?carts=${JSON.stringify(goods)}`,
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  // onReady: function () {

  // },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //  letaddname(this.data.carts)
    let that = this
    wx.showLoading({
      title: '正在获取购物车',
    })
    util.post({
      url:"https://groomtea.icebartech.com/api/miniApp/shoppingTrolley/shoppingTrolleyPage",
      data:{
        "pageIndex": 0,
        "pageSize": 99999
      },
      success:(res)=>{
        that.addname(res.data.bussData)
          .then(res=>{
           
            console.log(res);
            let carts = res;
            this.setData({ carts: carts })
            this.getTotalPrice();
            if (this.data.carts) {
              this.setData({
                hasList: true
              })
            }
          })
      },
      fail:(res)=>{
       
      },
      complete:()=>{
        wx.hideLoading();
      }
    })
  },
  addname(carts){
    console.log(carts);
    return new Promise((resolve,reject)=>{
    for(let i =0;i<carts.length;i++){
      carts[i].selected = false;
      carts[i].isTouchMove = false;
       util.post({
        url:'https://groomtea.icebartech.com/api/miniApp/product/productDetail',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data:{
          id:carts[i].productId
        },
        success:product=>{
          console.log(product);
          carts[i].name = product.data.bussData.productName;
          if(i==carts.length-1){
            resolve(carts);
          }
        },
        fail:err=>{
          if (i == carts.length - 1) {
            reject(err);
          }
        }
      })
    }
    })
    
  },
  

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getAllSelectStatus: function (carts) {
    let selectedCount = 0;
    for (let cart of carts) {
      if (cart.selected) {
        selectedCount++
      }
    }
    let isAllSelected = false;
    if (selectedCount == carts.length)
      isAllSelected = true
    return isAllSelected;
  },
  selectedList:function(e){
    let index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    carts[index].selected = !carts[index].selected;
    let isAllSeleted = this.getAllSelectStatus(carts);
    this.setData({
      carts,
      selectAllStatus: isAllSeleted
    })
    this.getTotalPrice();
  },
  deleteList:function(e){
    let index = e.currentTarget.dataset.index;
    let carts = this.data.carts; 
   carts = carts.filter((cart,i) =>{
     if(index == i){
      util.post({
         url:'https://groomtea.icebartech.com/api/miniApp/shoppingTrolley/deletedShoppingTrolley',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: {
          id: cart.id
        },
         method: 'POST',
         success:(res)=>{
          console.log(res)
        },
        fail:(err)=>{
          console.log(err)
        }
       })
     }
     return index != i;
   })
    this.setData({
      carts
    })
    if(!carts.length){
      this.setData({
        hasList:false
      })
    }
    this.getTotalPrice();
  },
  addCount:function(e){
    let index = e.currentTarget.dataset.index;
    let carts = this.data.carts; 
    carts[index].pieceNum && carts[index].pieceNum++;
    carts[index].bagNum && carts[index].bagNum++;
    let param = carts[index];
    util.post({
      url:'https://groomtea.icebartech.com/api/miniApp/shoppingTrolley/saveShoppingTrolley',
      data:param,
      success:(res) =>{
        console.log(res)
      }

    })
    this.setData({
      carts,
    })
    this.getTotalPrice();
  },
  minusCount: function (e) {
    let index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    carts[index].pieceNum && carts[index].pieceNum--;
    carts[index].bagNum && carts[index].bagNum--;
    let param = carts[index];
    util.post({
      url:'https://groomtea.icebartech.com/api/miniApp/shoppingTrolley/saveShoppingTrolley',
      data:param,
      success:(res) =>{
        console.log(res)
      }
      
    })
    this.setData({
      carts,
    })
    this.getTotalPrice();
  },
  selectAll:function(){
    let carts = this.data.carts;
    let Status = !this.data.selectAllStatus;
    for (let i = 0; i < carts.length; i++) {
      if (Status != carts[i].selected) {
        carts[i].selected = Status
      }
    }
    this.setData({
      carts,
      selectAllStatus: Status
    })
    this.getTotalPrice();
  },
   //手指触摸动作开始 记录起点X坐标
   touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.carts.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      carts: this.data.carts
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
      console.log(index)
      that.data.carts.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      carts: that.data.carts
    })
  },
  /** 
  * 计算滑动角度
  * @param {Object} start 起点坐标
  * @param {Object} end 终点坐标
  */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
})